#include <iostream>
#include <mutex>
#include <thread>

using std::cout;
using std::endl;
using std::mutex;
using std::thread;

mutex mtx;//创建了锁的对象

int gCnt = 0;

class MutexLockGuard
{
public:
    //在构造函数中上锁
    MutexLockGuard(mutex &mut)
    : _mtx(mut)
    {
        _mtx.lock();
    }

    //在析构函数中解锁
    ~MutexLockGuard()
    {
        _mtx.unlock();
    }
private:
    mutex &_mtx;
};
void threadFunc()
{
    for(size_t idx = 0; idx != 1000000; ++idx)
    {
        //利用栈对象的生命周期管理资源，使用的是RAII的思想
        MutexLockGuard mlg(mtx);//mlg栈对象
        ++gCnt;
    }
}

int main(int argc, char *argv[])
{
    thread thA(threadFunc);
    thread thB(threadFunc);

    thA.join();
    thB.join();

    cout << "gCnt = " << gCnt << endl;
    return 0;
}

